<?php
namespace app\car\model;
use app\BaseModel;
use think\facade\Db;



class ArticleStar extends BaseModel
{
    //定义表名
    protected $name = 'longbing_card_motor_article_star';


    /**
     * @author chenniang
     * @DataTime: 2021-05-11 16:00
     * @功能说明:添加
     */
    public function dataAdd($data){

//        $data['create_time'] = time();

        $res = $this->insert($data);

        return $res;

    }


    /**
     * @author chenniang
     * @DataTime: 2021-05-11 16:03
     * @功能说明:编辑
     */
    public function dataUpdate($dis,$data){

        $res = $this->where($dis)->update($data);

        return $res;

    }


    /**
     * @author chenniang
     * @DataTime: 2021-05-11 16:04
     * @功能说明:详情
     */
    public function dataInfo($dis){

        $data = $this->where($dis)->find();

        return !empty($data)?$data->toArray():[];

    }


    /**
     * @author chenniang
     * @DataTime: 2021-11-24 11:13
     * @功能说明:点赞 取消点赞
     */
    public function starUpdate($artcle_id,$user_id,$uniacid){

        $article_model = new ArticleList();

        $dis = [

            'article_id' => $artcle_id,

            'user_id'   => $user_id,

            'uniacid'   => $uniacid
        ];

        $find = $this->dataInfo($dis);

        Db::startTrans();

        if(!empty($find)){
            //取消点赞
            $res = $this->where($dis)->delete();

            if($res==0){

                Db::rollback();

                return ['code'=>500,'msg'=>'操作失败'];
            }

            $res = $article_model->where(['id'=>$artcle_id])->update(['star_num'=>Db::raw('star_num-1'),'total_num'=>Db::raw('total_num-1')]);

            if($res==0){

                Db::rollback();

                return ['code'=>500,'msg'=>'操作失败'];
            }


        }else{
            //点赞
            $res = $this->dataAdd($dis);

            if($res==0){

                Db::rollback();

                return ['code'=>500,'msg'=>'操作失败'];
            }

            $res = $article_model->where(['id'=>$artcle_id])->update(['star_num'=>Db::raw('star_num+1'),'total_num'=>Db::raw('total_num+1')]);

            if($res==0){

                Db::rollback();

                return ['code'=>500,'msg'=>'操作失败'];
            }

        }

        Db::commit();

        return true;

    }





    /**
     * @author chenniang
     * @DataTime: 2021-05-11 16:05
     * @功能说明:
     */
    public function dataList($dis,$page=10){

       $data = $this->alias('a')
                ->join('longbing_card_user b','a.user_id = b.id','left')
                ->where($dis)
                ->field('a.*,b.nickName,b.avatarUrl')
                ->group('a.id')
                ->order('a.id desc')
                ->limit($page)
                ->select()
                ->toArray();

       return $data;
    }





}